<template>
	<com-page :bg-color="skinColor.color_bg_1">
		<com-nav-bar :bg-color="skinColor.color_bg_1" :color="skinColor.color_1">
			<template #left>
				<com-icon name="close" size="40" :color="skinColor.color_1" @click="$Router.back()"></com-icon>
			</template>
			<template #title>
				<text class="fs-28 ml-20 lines-2 y-flex-1" :style="{color: skinColor.color_1}">{{loading ? '正在跳转网址..' : (title || nowSrc) }}</text>
			</template>
			<template #right>
				<com-icon class="ml-20" name="more" size="40" :color="skinColor.color_1" @click="toolbarShow = true"></com-icon>
			</template>
		</com-nav-bar>
		<yb-iframe
		ref="browser"
		class="y-flex-1"
		:src="src"
		:iframe-style="iframeStyle"
		:override-url-loading-options="{ mode: 'reject' }"
		console=""
		@backerror="handleBackError"
		@forwarderror="handleForwardError"
		@loaded="handleLoaded"
		@loadstart="handleLoadstart"
		@overrideurlloading="handleOverrideurlloading"></yb-iframe>
		<view class="y-flex">
			<view class="y-flex y-row y-align-center pt-25 pb-25 border-top-1" :style="{'border-top-color': skinColor.color_gap_1}">
				<view class="y-flex y-align-center y-flex-1">
					<com-icon name="back" :color="skinColor.color_3" size="40" @click="handleBack"></com-icon>
				</view>
				<view class="y-flex y-align-center y-flex-1">
					<com-icon name="right" :color="skinColor.color_3" size="40" @click="handleFoward"></com-icon>
				</view>
			</view>
			<com-safe-bottom></com-safe-bottom>
		</view>
		<com-popup direction="bottom" :visible.sync="websiteShow">
			<view class="popup-box" :style="{'background-color': skinColor.color_bg_2}" @touchmove.stop.prevent>
				<text class="fs-30 text-align-center" :style="{color: skinColor.color_3}">添加首页快捷方式</text>
				<input
				class="popup-box-input"
				v-model="websiteLogo"
				:style="{'background-color': skinColor.color_gap_1, 'color': skinColor.color_1}"
				placeholder="请输入logo地址（选填）" type="text" :placeholder-style="'color:' + skinColor.color_3" />
				<input
				class="popup-box-input"
				v-model="websiteTitle"
				:style="{'background-color': skinColor.color_gap_1, 'color': skinColor.color_1}"
				placeholder="请输入标题" max-length="20" type="text" :placeholder-style="'color:' + skinColor.color_3" />
				<input
				class="popup-box-input"
				v-model="websiteUrl"
				:style="{'background-color': skinColor.color_gap_1, 'color': skinColor.color_1}"
				placeholder="请输入网址/应用id" type="text" :placeholder-style="'color:' + skinColor.color_3" />
				<view class="y-flex y-row y-align-center mt-45 ml-10" @tap="websiteIsAdult = websiteIsAdult ? 0 : 1" v-if="$store.getters['setting/GET_ADULT']">
					<com-icon size="40" :name="websiteIsAdult ? 'square_check_fill' : 'square'" :color="websiteIsAdult ? skinColor.color_blue : skinColor.color_3"></com-icon>
					<text class="fs-29 ml-5" :style="{color: skinColor.color_3}">包含敏感信息</text>
				</view>
				<view class="y-flex y-row mt-60">
					<com-button class="popup-box-btn y-flex-1"
					:bg-color="skinColor.color_3" :color="skinColor.color_3" radius="80rpx" size="30" plain value="取消创建"
					@click="websiteShow = false" />
					<com-gap width="60rpx"></com-gap>
					<com-button class="popup-box-btn y-flex-1"  radius="80rpx" size="30" type="primary" value="确认创建"
					@click="handleWebsiteConfirm" />
				</view>
			</view>
		</com-popup>
		<com-popup direction="center" :visible.sync="qrcodeShow">
			<view class="qrcode-box y-flex y-align-center y-justify-center"
			:style="{'background-color': skinColor.color_bg_2}" @touchmove.stop.prevent>
				<text class="fs-28 mb-30" :style="{color: skinColor.color_1}">请使用其它设备扫描二维码</text>
				<com-qrcode ref="qrcode" correct-level="3" :colorDark="colorDark" :colorLight="colorLight" :text="qrcodeText" />
				<view class="y-flex y-row y-align-center mt-30">
					<com-button style="width: 200rpx;" value="取消" @click="qrcodeShow = false"></com-button>
					<com-gap width="20rpx"></com-gap>
					<com-button style="width: 200rpx;" type="error" value="保存" @click="saveQrcode"></com-button>
				</view>
			</view>
		</com-popup>
		<com-toolbar radius="5" :top="windowTop + 'px'" width="350" :visible.sync="toolbarShow" :bg-color="skinColor.color_bg_2">
			<com-toolbar-item :color="skinColor.color_1" text="浏览记录" @click="handleRecord"></com-toolbar-item>
			<com-toolbar-item :color="skinColor.color_1" text="软件设置" @click="$Router.push({path: '/pages/my/setting'})"></com-toolbar-item>
			<com-toolbar-item :color="skinColor.color_1" text="分享网页" @click="handleShare"></com-toolbar-item>
			<com-toolbar-item :color="skinColor.color_1" text="复制网页" @click="handleCopy"></com-toolbar-item>
			<com-toolbar-item :color="skinColor.color_1" text="刷新网页" @click="handleReload"></com-toolbar-item>
			<com-toolbar-item :color="skinColor.color_1" text="生成二维码" @click="handleQrcode"></com-toolbar-item>
			<com-toolbar-item :color="skinColor.color_1" text="快捷方式" @click="handleShortcut"></com-toolbar-item>
			<com-toolbar-item :color="skinColor.color_1" text="浏览器打开" @click="handleOther"></com-toolbar-item>
		</com-toolbar>
		<com-dialog ref="dialog" />
	</com-page>
</template>

<script>
	import appMixin from '@/assets/mixin/app.js'
	import { openDB, closeDB, insert, update } from '@/assets/database'
	export default {
		mixins: [appMixin],
		computed: {
			iframeStyle () {
				return this.skinMode == 'night' ? 'filter: invert(1)' : 'filter: invert(0)'
			},
			colorDark () {
				return this.skinMode == 'default' ? '#000' : '#fff'
			},
			colorLight () {
				return this.skinMode == 'default' ? '#fff' : '#000'
			},
			videoFullscreen () {
				return this.$store.getters['setting/GET_VIDEO_FULLSCREEN']
			}
		},
		data () {
			return {
				logo: '',//当前访问站点logo
				nowSrc: '',//当前访问站点链接
				title: '',//当前访问站点标题
				src: '',//初始访问站点链接
				isAdult: 0,
				loading: true,//加载中
				toolbarShow: false,//显示工具栏
				websiteLogo: '',//网站logo
				websiteTitle: '',//网站标题
				websiteUrl: '',//网站地址
				websiteIsAdult: 0,//是否敏感网站
				websiteShow: false,//展示网站编辑
				qrcodeShow: false,//展示二维码
				qrcodeText: ''//二维码内容
			}
		},
		onLoad() {
			this.src = this.$Route.query.src
			this.isAdult = this.$Route.query.isAdult || 0
		},
		onReady() {
			this.setFullscreen()
		},
		methods: {
			handleLoaded (e) {
				this.setCss()
				if ( !this.$store.getters['setting/GET_NOTRACE'] ) {
					openDB().then(() => {
						insert('history', {title: e.title, href: e.href, is_adult: parseInt(this.isAdult)}).then(() => {
							closeDB()
						}).catch(err => {
							closeDB()
							uni.showToast({
								title: err.message,
								icon: 'none'
							})
						})
					})
				}
				this.logo = e.favicon
				this.title = e.title
				this.nowSrc = e.href
				this.loading = false
			},
			handleLoadstart () {
				this.loading = true
			},
			handleBack () {
				this.$refs.browser && this.$refs.browser.back()
			},
			handleFoward () {
				this.$refs.browser && this.$refs.browser.forward()
			},
			handleBackError () {
				this.$Router.back()
			},
			handleForwardError () {
				uni.showToast({
					title: '前进到最后面了',
					icon: 'none'
				})
			},
			handleOverrideurlloading (e) {
				if ( e.url.slice(0, 4) == 'http' ) {
					this.$refs.browser && this.$refs.browser.assign(e.url)
				} else {
					this.$refs.dialog.confirm({
						title: '拦截提示',
						content: '网站试图跳转未知地址：\n\n' + e.url + '\n\n可能会有风险，已拦截该行为',
						confirmText: '干得漂亮',
						cancelText: '继续访问',
						complete: res => {
							if ( res && !res.confirm ) {
								this.$refs.browser && this.$refs.browser.assign(e.url)
							} else {
								this.$refs.browser && this.$refs.browser.hideLoading()
							}
						}
					})
				}
			},
			handleRecord () {
				this.toolbarShow = false
				this.$Router.push({
					path: '/pages/browser/history',
					complete: () => {
						uni.$once('browser_history', e => {
							this.src = e.detail.href
						})
					}
				})
			},
			handleShare () {
				this.$native.shareText(this.title + '\n' + this.nowSrc)
				this.toolbarShow = false
			},
			handleCopy () {
				this.$utils.copyText(this.title + '\n' + this.nowSrc)
				this.toolbarShow = false
			},
			handleReload () {
				this.$refs.browser && this.$refs.browser.reload()
				this.toolbarShow = false
			},
			handleShortcut () {
				this.websiteLogo = this.logo
				this.websiteTitle = this.title
				this.websiteUrl = this.nowSrc
				this.websiteShow = true
			},
			//生成二维码
			handleQrcode () {
				if ( !this.nowSrc ) {
					uni.showToast({
						title: '请先等待网页加载完成',
						icon: 'none'
					})
					return
				}
				this.qrcodeText = this.nowSrc
				this.qrcodeShow = true
				this.toolbarShow = false
			},
			//保存二维码
			saveQrcode () {
				this.$refs.qrcode.toTempFilePath({
					complete: res => {
						if ( res.errCode == 0 ) {
							this.$native.saveBase64ImageToAlbum(res.data.base64, this.title + this.$utils.randomString(4) + '网址.jpg').then(res => {
								uni.showToast({
									title: '成功保存到相册',
									icon: 'none'
								})
							}).catch(() => {
								uni.showToast({
									title: '保存到相册失败',
									icon: 'none'
								})
							})
						} else {
							uni.showToast({
								title: res.errMsg,
								icon: 'none'
							})
						}
					}
				})
			},
			handleOther () {
				this.toolbarShow = false
				plus.runtime.openURL(this.nowSrc)
			},
			setCss () {
				const value = this.skinMode == 'night' ? 1 : 0
				this.$refs.browser && this.$refs.browser.evalCSS(`
					video, img {
					  filter: invert(${value});
					}
				`)
			},
			setFullscreen () {
				const wv = this.$scope.$getAppWebview()
				const fulls = ['auto', 'landscape', 'portrait']
				wv.setStyle({
					videoFullscreen: fulls[this.videoFullscreen]
				})
			},
			async handleWebsiteConfirm () {
				if ( !this.websiteTitle ) {
					uni.showToast({
						title: '请输入网址标题',
						icon: 'none'
					})
					return
				}
				if ( !this.websiteUrl ) {
					uni.showToast({
						title: '请输入网址链接',
						icon: 'none'
					})
					return
				}
				this.websiteShow = false
				try{
					await openDB()
					await insert('shortcut', {title: this.websiteTitle, logo: this.websiteLogo, url: this.websiteUrl, is_adult: this.websiteIsAdult})
					uni.showToast({
						title: '添加成功',
						icon: 'none'
					})
				}catch(e){
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
				}
				closeDB()
			}
		},
		onBackPress(event) {
			if ( event.from == 'backbutton' ) {
				if ( this.qrcodeShow ) {
					this.qrcodeShow = false
					return true
				}
				if ( this.websiteShow ) {
					this.websiteShow = false
					return true
				}
				if ( this.toolbarShow ) {
					this.toolbarShow = false
					return true
				}
				if ( this.$refs.dialog.modal.show ) {
					this.$refs.dialog.modal.show = false
					return true
				}
				this.$refs.browser && this.$refs.browser.back()
				return true
			}
			return false
		},
		watch: {
			skinMode () {
				this.setCss()
			},
			videoFullscreen () {
				this.setFullscreen()
			}
		}
	}
</script>

<style>
	.qrcode-box {
		width: 500rpx;
		height: 500rpx;
	}
</style>